<template>
  <div class="page-Body" v-if="!$route.params.id">
    <h2 class="page-title">社群管理</h2>
    <!-- 表单 -->
    <el-form :inline="true" :model="formInline">
      <el-form-item label="社群名称">
        <el-input
          v-model="formInline.name"
          placeholder="请输入社群名称"
          clearable
          style="width: 180px"
          v-noSpace
        />
      </el-form-item>
      <el-form-item label="社群分类">
        <el-select
          v-model="formInline.typeId"
          placeholder="请选择标签分类"
          clearable
          @focus="getClick"
          style="width: 180px"
          :loading="load"
        >
          <el-option
            v-for="item in tagSelectList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <TimeFormatter
          @TimeChild="TimeHandle"
          ref="childComponentRef"
          style="width: 350px"
        ></TimeFormatter>
      </el-form-item>
      <el-form-item label="发起人">
        <el-input
          v-model="formInline.founderUid"
          placeholder="请输入发起人"
          clearable
          style="width: 180px"
          v-noSpace
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="Search">搜索</el-button>
        <el-button @click="Reset">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 表格 -->
    <el-table
      :data="tableData"
      border
      stripe
      fit
      empty-text="暂无数据"
      show-header
      v-loading="loading"
      size="default"
      element-loading-text="Loading..."
      :header-cell-style="{ background: '#e7e1fb' }"
      style="width: 100%"
      max-height="600px"
    >
      <el-table-column type="index" label="序号" width="80" align="center" />
      <el-table-column prop="name" label="社群名称" />
      <el-table-column prop="typeName" label="社群分类" />
      <el-table-column prop="tags" label="社群标签" v-slot="scope" width="200">
        <el-tag
          v-for="(item, index) in scope.row.tags || []"
          :key="index"
          style="margin-right: 5px"
        >
          {{ item }}
        </el-tag>
      </el-table-column>
      <el-table-column prop="releaseTime" label="发起时间" />
      <el-table-column prop="founderUid" label="社群创建人" />
      <el-table-column prop="ownerName" label="群主" />
      <el-table-column prop="member" label="成员数" />
      <el-table-column prop="sort" label="排序" />
      <el-table-column prop="removed" label="下架" />
      <el-table-column
        align="center"
        fixed="right"
        label="操作"
        v-slot="scope"
        :show-overflow-tooltip="true"
        width="500"
      >
        <el-button link type="primary" @click="Details(scope.row)">
          详情
        </el-button>
        <el-button
          link
          type="primary"
          @click="CommunityMember(scope.row.communityId)"
        >
          成员
        </el-button>
        <el-button
          link
          type="primary"
          @click="MessageWall(scope.row.communityId)"
        >
          留言墙
        </el-button>
        <el-button
          link
          type="primary"
          @click="CommunityActivity(scope.row.communityId)"
        >
          活动
        </el-button>
        <el-button
          link
          type="primary"
          @click="SuperGroup(scope.row.communityId)"
        >
          超级群
        </el-button>

        <el-button link type="primary" @click="Resource(scope.row.communityId)">
          资源消息群
        </el-button>
        <!-- 排序 -->
        <el-input-number
          v-model="scope.row.sort"
          :min="0"
          style="width: 80px"
          size="small"
          controls-position="right"
          @change="(val) => Sort(val, scope.row.communityId)"
        />
        <el-button
          link
          type="danger"
          @click="CommunityRemoval(scope.row.communityId)"
          :disabled="scope.row.removed === '是'"
          :style="
            scope.row.removed === '是'
              ? { color: '#999', cursor: 'not-allowed' }
              : {}
          "
        >
          群下架
        </el-button>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <div class="pagination-block">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[20, 40, 80, 100]"
        background
        layout="total,sizes, prev, pager, next,jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 社群下架对话框 -->
    <GroupDelisting
      @confirm="RemovalConfirm"
      @cancel="RemovalClose"
      :communityId="communityId"
      :dialogRemoval="dialogRemoval"
    />
    <AssociationDetail_Dialog
      @cancel="DetailsClose"
      :dialogDetails="dialogDetails"
      :DetailsRow="DetailsRow"
    />
  </div>
  <div v-else>
    <router-view :key="$route.fullPath"></router-view>
  </div>
</template>

<script setup name="CommunityManagementPage">
import {
  getCommunityList,
  getCommunityCategory,
  updateCommunitySort,
} from '@/api/Association/ment.js';
import TimeFormatter from '@/components/permission/TimeFormatter.vue';
import GroupDelisting from '@/components/association/GroupDelisting.vue';
import AssociationDetail_Dialog from '@/components/association/AssociationDetail_Dialog.vue';
import { ref, onMounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';

const route = useRoute();
const router = useRouter();

// 分页变量
const currentPage = ref(1);
const pageSize = ref(20);
const total = ref(0);
// 表单-时间选择器
const childComponentRef = ref(null);
const TimeArray = ref([]);
// 表单数据
const formInline = ref({
  name: '',
  typeId: '',
  founderUid: '',
});
const communityId = ref('');
// 社群分类下拉
const load = ref(false);
const tagSelectList = ref([]);
// 时间变量
const startDate = ref('');
const endDate = ref('');
const DetailsRow = ref({});
// 对话框
const dialogRemoval = ref(false);
const dialogDetails = ref(false);
// 列表数据+表单校验
const tableData = ref([]);
const loading = ref(true);
// 防抖函数
let timer = null;
const debounce = (fn, delay = 500) => {
  if (timer) clearTimeout(timer);
  timer = setTimeout(() => {
    fn();
    timer = null;
  }, delay);
};
// 分页逻辑
const handleSizeChange = async (val) => {
  pageSize.value = val;
  CommunityList();
};
const handleCurrentChange = (val) => {
  currentPage.value = val;
  CommunityList();
};
// 获取列表
const CommunityList = async () => {
  loading.value = true;
  const res = await getCommunityList({
    current: currentPage.value,
    size: pageSize.value,
    startDate: TimeArray.value[0],
    endDate: TimeArray.value[1],
    query: { ...formInline.value },
  });
  if (res.data.code === 200) {
    tableData.value = res.data.data.items;
    total.value = res.data.data.counts || 0;
    loading.value = false;
  }
};
const getClick = () => {
  CommunityCategory();
};
// 获取社群分类下拉
const CommunityCategory = async () => {
  if (tagSelectList.value.length > 0) return; // 如果已有数据则不重复获取
  load.value = true;
  const res = await getCommunityCategory({});
  if (res.data.code === 200) {
    tagSelectList.value = res.data.data;
    load.value = false;
  }
};
// 搜索校验
const hasSearchConditions = () => {
  const { name, typeId, founderUid } = formInline.value;
  return (
    name ||
    typeId ||
    founderUid ||
    (TimeArray.value &&
      TimeArray.value.length === 2 &&
      TimeArray.value.every((date) => date))
  );
};
// 搜索
const Search = async () => {
  if (!hasSearchConditions()) {
    ElMessage({
      message: '请至少输入一个搜索条件或选择完整的时间范围',
      type: 'warning',
    });
    return;
  }
  CommunityList();
};
// 重置
const Reset = () => {
  // 如果当前已经是空值状态，直接返回
  if (
    formInline.value.name === '' &&
    formInline.value.typeId === '' &&
    formInline.value.founderUid === '' &&
    (!TimeArray.value || TimeArray.value.length === 0)
  ) {
    return;
  }
  formInline.value = {
    name: '',
    typeId: '',
    founderUid: '',
  };
  TimeArray.value = [];
  if (childComponentRef.value) {
    childComponentRef.value.clear();
  }
  CommunityList();
};
//获取时间
const TimeHandle = (data) => {
  TimeArray.value = data;
};
// 下架对话框
const CommunityRemoval = (Id) => {
  dialogRemoval.value = true;
  communityId.value = Id;
};
const RemovalConfirm = () => {
  dialogRemoval.value = false;
  CommunityList();
};
const RemovalClose = () => {
  dialogRemoval.value = false;
};
// 查看社群详情
const Details = (row) => {
  dialogDetails.value = true;
  DetailsRow.value = row;
};
const DetailsClose = () => {
  dialogDetails.value = false;
};
// 查看社群成员
const CommunityMember = (id) => {
  handleRouteChange('communitymentMember', id);
};
// 社群活动
const CommunityActivity = (id) => {
  router
    .push({
      name: 'activityment',
      params: { communityId: id },
    })
    .catch((err) => {
      console.error('路由跳转失败:', err);
    });
};
// 查看留言墙
const MessageWall = (id) => {
  handleRouteChange('MessageWall', id);
};
// 查看超级群
const SuperGroup = (id) => {
  handleRouteChange('SuperGroup', id);
};
// 查看资源消息群
const Resource = (id) => {
  handleRouteChange('resource', id);
};
// 排序
const Sort = async (value, id) => {
  debounce(async () => {
    try {
      loading.value = true;
      const res = await updateCommunitySort({
        communityId: id,
        sort: value,
      });
      if (res.data.code === 200) {
        // eslint-disable-next-line no-undef
        ElMessage({
          message: '排序修改成功',
          type: 'success',
        });
      } else {
        // eslint-disable-next-line no-undef
        ElMessage({
          message: res.data.msg,
          type: 'error',
        });
      }
    } catch (error) {
      console.error('排序修改失败:', error);
    } finally {
      loading.value = false;
    }
  });
};
// 监听路由参数变化
watch(
  () => route.params.id,
  (newId) => {
    if (newId) {
      // 当路由参数变化时，可以在这里处理相应的逻辑
    }
  },
  { immediate: true }
);
// 优化路由跳转方法
const handleRouteChange = (name, id) => {
  router
    .push({
      name,
      params: { id },
    })
    .catch((err) => {
      console.error('路由跳转失败:', err);
    });
};
onMounted(() => {
  CommunityList();
});
</script>

<style lang="scss" scoped></style>
